#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Thread.hpp"
#include "UdpServer.hpp"
#include "Comm.hpp"

using namespace std;
using namespace yss;

void Usage(string proc)
{
    cout << "Usage: " << proc << " + ip + proc" << endl;
}

int InitClient(string &serverip, uint16_t serverport, struct sockaddr_in *server)
{
    // 创建socket套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cout << "create fail" << endl;
    }

    // bind 由OS实现，不需要使用者显示bind
    // 什么时候？传数据的时候
    // 为什么？bind与port关联，防止client port冲突
    // 如何做到的？OS执行

    // 构建目标主机socket信息
    memset(server, 0, sizeof(struct sockaddr_in)); // ！！
    server->sin_family = AF_INET;
    server->sin_port = htons(serverport);
    server->sin_addr.s_addr = inet_addr(serverip.c_str());
    return sockfd;
}

void recvmessage(int sockfd, string name)
{
    int fd = OpenDev("/dev/pts/2", O_WRONLY);
    while(true)
    {
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(len);
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
        if (n > 0)
        {
            buffer[n] = 0;
            //printf("%s | %s\n", name.c_str(), buffer);
            write(fd, buffer, strlen(buffer));
        }
    }
}

void sendmessage(int sockfd, struct sockaddr_in &server, string name)
{
    string message; 
    while(true)
    {
        printf("%s | Enter# ", name.c_str());
        fflush(stdout);
        getline(cin, message); // 客户端发送信息
        sendto(sockfd, message.c_str(), sizeof(message) - 1, 0, (struct sockaddr *)&server, sizeof(server));
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    struct sockaddr_in serveraddr;
    int sockfd = InitClient(serverip, serverport, &serveraddr);
    if(sockfd == -1) return 1;

    func_t r = bind(&recvmessage, sockfd, placeholders::_1);
    func_t s = bind(&sendmessage, sockfd, serveraddr, placeholders::_1);

    Thread Recver(r, "recver"); // 收
    Thread Sender(s, "sender"); // 发

    Recver.Start();
    Sender.Start();

    Recver.Join();
    Sender.Join();
}